﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using MasterDetailTemplate.Services;

namespace MasterDetailTemplate.ViewModels {
    /// <summary>
    /// 初始化页viewmodel。
    /// By WZC
    /// </summary>
    public class InitializationPageViewModel : ViewModelBase {
        /// <summary>
        /// 事件存储。
        /// </summary>
        private IEventStorage _eventStorage;

        /// <summary>
        /// 根导航。
        /// </summary>
        private IRootNavigationService _rootNavigationService;

        /// <summary>
        /// 初始化数据库viewmodel。
        /// </summary>
        /// <param name="eventStorage">事件存储。</param>
        /// <param name="rootNavigationService">根导航。</param>
        public InitializationPageViewModel(IEventStorage eventStorage,
            IRootNavigationService rootNavigationService) {
            _eventStorage = eventStorage;
            _rootNavigationService = rootNavigationService;
        }

        /// <summary>
        /// 状态。
        /// </summary>
        public string Status {
            get => _status;
            set => Set(nameof(Status), ref _status, value);
        }

        /// <summary>
        /// 状态。
        /// </summary>
        private string _status;

        /// <summary>
        /// 页面显示命令。
        /// </summary>
        private RelayCommand _pageAppearingCommand;

        /// <summary>
        /// 页面显示命令。
        /// </summary>
        public RelayCommand PageAppearingCommand =>
            _pageAppearingCommand ?? (_pageAppearingCommand =
                new RelayCommand(async () =>
                    await PageAppearingCommandFunction()));

        /// <summary>
        /// 页面显示命令。
        /// </summary>
        public async Task PageAppearingCommandFunction() {
            var run = false;

            if (!pageLoaded) {
                lock (pageLoadedLock) {
                    if (!pageLoaded) {
                        pageLoaded = true;
                        run = true;
                    }
                }
            }

            if (!run)
                return;

            if (!_eventStorage.Initialized()) {
                Status = "正在初始化事件数据库";
                await _eventStorage.InitializeAsync();
            }

            Status = "完成初始化";
            await Task.Delay(1000);

            await _rootNavigationService.NavigateToAsync(
                RootNavigationServiceConstants.HomePage);
        }

        /// <summary>
        /// 页面已加载。
        /// </summary>
        private volatile bool pageLoaded;

        /// <summary>
        /// 页面已加载锁。
        /// </summary>
        private readonly object pageLoadedLock = new object();
    }
}